package com.jghz.framework.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.hibernate.util.StringHelper;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.IDao;
import com.bstek.bdf2.core.service.IUserService;
import com.bstek.dorado.core.Configure;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.jghz.framework.base.JdbcDao;
import com.jghz.framework.exception.AppException;

/**
 * @ClassName AppUtils
 * @Description 公用方法
 * @author 魏甘
 * @Date 2016-10-28 上午11:14:50
 * @version 1.0.0
 */
public final class AppUtils {

	public static String validateAndGetValue(Map map, String key) {
		if (AppUtils.isEmpty(map.get(key)))
			throw new AppException("传入参数不得为空" + key);
		else
			return map.get(key).toString();
	}

	public static void validateValue(String key, String value) {
		if (AppUtils.isEmpty(value))
			throw new AppException("传入参数不得为空" + key);
	}

	public static String toString(Object obj) {
		return ((obj == null) ? "" : obj.toString().trim());
	}

	public static Date getCurrentDate() {
		return new Date();
	}

	public static String getCurrentDateString(String formatStr) {
		SimpleDateFormat sd = new SimpleDateFormat(formatStr);
		return sd.format(new Date());
	}

	/**
	 * 将一个 JavaBean 对象转化为一个 Map
	 *
	 * @param bean
	 *            要转化的JavaBean 对象
	 * @return 转化出来的 Map 对象
	 * @throws IntrospectionException
	 *             如果分析类属性失败
	 * @throws IllegalAccessException
	 *             如果实例化 JavaBean 失败
	 * @throws InvocationTargetException
	 *             如果调用属性的 setter 方法失败
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map convertBean(Object bean)
			throws IntrospectionException, IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map returnMap = new HashMap();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);

		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					returnMap.put(propertyName, result);
				} else {
					// returnMap.put(propertyName, "");
				}
			}
		}
		return returnMap;
	}

	/**
	 * @Description 判断对象是否为null或空字符串
	 * @param s
	 * @return
	 */
	public static boolean isNotEmpty(Object s) {
		if (s == null)
			return false;
		else if (s.toString().length() > 0)
			return true;
		else
			return false;
	}

	/**
	 * @Description 判断对象是否为null或空字符串
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(Object s) {
		if (s == null)
			return true;
		else if (s.toString().length() > 0)
			return false;
		else
			return true;
	}

	/**
	 * @Description 获取唯一ID
	 * @return
	 */
	public static String generateUniqueKey() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 获取用户服务
	 *
	 * @return
	 */
	public static IUserService getUserService() {
		return (IUserService) SpringHolder.getBean("bdf2.userService");
	}

	public static IUser getUserByName(String name) {
		IUserService iUserService = (IUserService) SpringHolder.getBean("bdf2.userService");
		return (IUser) iUserService.loadUserByUsername(name);
	}

	/**
	 * @Description 获取登录人信息
	 * @return
	 */
	public static IUser getLoginIUser() {
		IUser iuser = ContextHolder.getLoginUser();
		if (iuser == null)
			throw new AppException("请重新登录！！");
		// DefaultUser user = new DefaultUser();
		// return user;
		return iuser;
	}

	/**
	 * @Description 获取登录人名字
	 * @return
	 */
	public static String getLoginUserName() {
		String name = ContextHolder.getLoginUserName();
		if (AppUtils.isNotEmpty(name))
			return name;
		else
			throw new AppException("请重新登录！！");
	}

	/**
	 * @Description 获取登录人公司别
	 * @return
	 */
	public static String getLoginUserCompId() {
		IUser userInfo = getLoginIUser();
		String compId = Configure.getString(IDao.FIXED_COMPANY_ID);
		if (userInfo != null && StringUtils.isNotEmpty(userInfo.getCompanyId()))
			return userInfo.getCompanyId();
		else
			return compId;
	}

	/**
	 * @Description 转为字符串，为空就返回0
	 * @param o
	 * @return
	 */
	public static String emptyString2Zero(Object o) {
		if (o == null)
			return "0";
		if (StringUtils.isEmpty(o.toString()))
			return "0";
		return o.toString();
	}

	/**
	 * @Description 对象转BigDecimal
	 * @param value
	 * @return
	 */
	public static BigDecimal getBigDecimal(Object value) {
		BigDecimal ret = null;
		if (value != null) {
			if (value instanceof BigDecimal) {
				ret = (BigDecimal) value;
			} else if (value instanceof String) {
				ret = new BigDecimal(emptyString2Zero(value));
			} else if (value instanceof BigInteger) {
				ret = new BigDecimal((BigInteger) value);
			} else if (value instanceof Number) {
				ret = BigDecimal.valueOf(((Number) value).doubleValue());
			} else
				throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
						+ " into a BigDecimal.");
		} else {
			ret = BigDecimal.ZERO;
		}
		return ret;
	}

	/*
	 * 自定义方法,转换数据库字段为类字段 若结果有重复key(如xc01_id_,xc01_id),结果将保存包含value的那一个
	 */
	public static List<Map<String, Object>> convertKey(List<Map<String, Object>> list) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> map : list) {
			Map<String, Object> resultMap = new HashMap<>();
			Set<Entry<String, Object>> set = map.entrySet();
			for (Entry<String, Object> entry : set) {
				String key = entry.getKey();
				String resultKey = parseKey(key);
				if (resultMap.containsKey(resultKey) && StringHelper.isNotEmpty((String) resultMap.get(resultKey))) {

				} else {
					resultMap.put(resultKey, entry.getValue());
				}
			}
			result.add(resultMap);
		}
		return result;
	}

	/*
	 * 字符串转换，Comp_Id_ to compId
	 */
	public static String parseKey(String key) {
		String[] arr = key.split("_");
		String result = "";
		int index = 0;
		for (String string : arr) {
			if ((index++) == 0) {
				result += string.toLowerCase();
			} else {
				result += ((string.substring(0, 1).toUpperCase()) + (string.substring(1).toLowerCase()));
			}
		}
		return result;
	}

	/**
	 * @Description 字符串补0
	 * @param str
	 *            字符串
	 * @param count
	 *            字符总长度
	 * @return String
	 */
	public static String addZero(String str, int count) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < count - str.length(); i++) {
			sb.append("0");
		}
		sb.append(str);
		str = sb.toString();
		return str;
	}

	/**
	 * 判断输入字符串是否为科学计数法
	 */
	public static boolean isENum(String input) {
		String regx = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";// 科学计数法正则表达式
		Pattern pattern = Pattern.compile(regx);
		return pattern.matcher(input).matches();
	}

	/**
	 * 去除数字里多余的0
	 */
	public static String getPrettyNumber(Object number) {
		if (null != number)
			return BigDecimal.valueOf(Double.parseDouble(number.toString())).stripTrailingZeros().toPlainString();
		else
			return "0";
	}

	/**
	 * 生成6位数验证码
	 *
	 * @return
	 */
	public static String createCode() {
		Long xx = Math.round(Math.random() * 1000000);
		while (xx < 100000) {
			xx = Math.round(Math.random() * 1000000);
		}
		return String.valueOf(xx);
	}

	public static String[] getNullPropertyNames(Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (java.beans.PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null) {
				emptyNames.add(pd.getName());
			}
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	/**
	 *
	 * @return MAP {empNo,empName}
	 */
	public static BiMap<String, String> getUserCollection() {
		JdbcDao jdbcDao = SpringHolder.getBean(JdbcDao.class);
		BiMap<String, String> userMap = HashBiMap.create();
		String sql = "select distinct a.USERNAME_ as empNo ,a.CNAME_ as empName  from bdf2_user as a";
		List<Map<String, Object>> list = jdbcDao.getJdbcTemplate().queryForList(sql);
		for (Map<String, Object> map : list) {
			userMap.put(AppUtils.toString(map.get("empName")), AppUtils.toString(map.get("empNo")));
		}
		return userMap;
	}

	/**
	 *
	 * @return MAP {deptName,deptNo}
	 */
	public static BiMap<String, String> getDeptCollection() {
		JdbcDao jdbcDao = SpringHolder.getBean(JdbcDao.class);
		BiMap<String, String> userMap = HashBiMap.create();
		String sql = "select distinct a.ID_ as deptNo ,a.NAME_ as deptName  from bdf2_dept as a";
		List<Map<String, Object>> list = jdbcDao.getJdbcTemplate().queryForList(sql);
		for (Map<String, Object> map : list) {
			userMap.put(AppUtils.toString(map.get("deptName")), AppUtils.toString(map.get("deptNo")));
		}
		return userMap;
	}

	public static void cleanDirectory(String pathname) {
		File file = new File(pathname);
		try {
			if (file.exists()) {
				if (file.isFile()) {
					FileUtils.forceDelete(file);
				} else if (file.isDirectory()) {
					FileUtils.deleteDirectory(file);
				}
			}
			FileUtils.forceMkdir(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
